package org.example.book.controller;

import jakarta.servlet.http.HttpSession;
import org.example.book.constants.Constants;
import org.example.book.model.Result;
import org.example.book.model.UserInfo;
import org.example.book.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping(value = "/login",produces = "application/json")
    public Result login(String userName, String password, HttpSession session){
        //1.校验参数
        //2.验证密码正确性
        //3.返回响应
        if(!StringUtils.hasLength(userName)||!StringUtils.hasLength(password)){
            return Result.fail("用户名或密码为空") ;
        }
        //理论上英嘎从数据库获取 先模拟校验
        /*if("admin".equals(userName)&&"admin".equals(password)){
            return "";
        }
        return "密码错误";*/

        //代码少的写在前面
        //差不多的话 套方法
        if(!"admin".equals(userName) || !"admin".equals(password)){
            return Result.fail("密码错误");
        }

        //根据用户名称查询用户信息 未查到说明用户不存在
        //查询到 比对密码
        UserInfo userInfo = userService.getUserInfoByName(userName);
        if(userInfo == null){
            return Result.fail("用户不存在");
        }
        if(!password.equals(userInfo.getPassword())){
            return Result.fail("密码不正确");
        }
        //正确的情况
        session.setAttribute(Constants.USER_SESSION_KEY,userInfo);
        return Result.success("");

    }
}
